import shutil
import requests
import pymongo
import os

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client.get_database("率土之滨")
collection = db.get_collection("武将库")

hero_url = "https://g0.gph.netease.com/ngsocial/community/stzb/cfg/hero_extra.json?gameid=g10"

req = requests.get(hero_url)
response = req.json()

collection.insert_many(response)
client.close()

directory_path = 'static/率土之滨'
if not os.path.exists(directory_path):
    os.makedirs(directory_path)
else:
    shutil.rmtree(directory_path)
    os.makedirs(directory_path)


for item in response:
    hero_id = item.get("id")
    hero_name = item.get("name")
    hero_icon_url = f'https://g0.gph.netease.com/ngsocial/community/stzb/cn/cards/cut/card_small_{hero_id}.jpg?gameid=g10'
    hero_icon_response = requests.get(hero_icon_url)

    with open(f"{directory_path}/{hero_name}.jpg", "wb") as f:
        f.write(hero_icon_response.content)



